package middleware

import (
	"github.com/gin-gonic/gin"
	"iot-base/auth/model"
	"iot-base/auth/svc"
	"strings"
	"time"
)

func OperationLogsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next()
		uid := c.GetInt64("uid")
		reqStatus := c.GetString("ReqStatus")
		userInfo, _ := svc.Dao.TUser.GetById(uid)
		data := model.OperationLogs{
			UserName:  userInfo.UserName,
			UserId:    uid,
			Method:    c.Request.Method,
			Action:    c.Request.RequestURI,
			Title:     "",
			Ip:        c.ClientIP(),
			UserAgent: c.Request.UserAgent(),
			CreatedAt: model.Datetime(time.Now()),
		}
		if strings.Contains(c.Request.RequestURI, "login") {
			data.Title = "登录"
			data.LogType = "login"
		} else if strings.Contains(c.Request.RequestURI, "signOut") {
			data.Title = "注销"
			data.LogType = "login"
		} else {
			data.LogType = "other"
		}
		data.Status = reqStatus
		svc.Dao.TOperationLog.Add(&data)
	}
}
